package com.tangji.signaltower.websocket.session;

import com.fqgj.common.utils.CollectionUtils;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2020-09-17
 * Time: 11:58
 */
public class UserGroup {

    private static final Logger logger = LoggerFactory.getLogger(UserGroup.class);

    //所有的用户map
    private Map<String, ServerSession> allSessionMap = new HashMap<>();

    //一般用户的channel组
    private ChannelGroup normalUserChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //key为sessionId,value为当前用户的serverSession
    private Map<String, ServerSession> fakeUserSessionIdMap = new HashMap<>();


    public ChannelGroup getNormalUserChannels() {
        return normalUserChannels;
    }

    public Map<String, ServerSession> getFakeUserSessionIdMap() {
        return fakeUserSessionIdMap;
    }

    public Map<String, ServerSession> getAllSessionMap() {
        return allSessionMap;
    }

    public void addNormalUser(ServerSession serverSession) {
        logger.info("==UserGroup 加入到普通用户  ==,sessionId:{}", serverSession.getSessionId());
        allSessionMap.put(serverSession.getSessionId(), serverSession);
        normalUserChannels.add(serverSession.getChannel());
        fakeUserSessionIdMap.remove(serverSession.getSessionId());
    }

    public void addFakeUser(ServerSession serverSession) {
        logger.info("==UserGroup 加入到fake用户  ==,sessionId:{}", serverSession.getSessionId());
        if (normalUserChannels != null) {
            normalUserChannels.remove(serverSession.getChannel());
        }


        allSessionMap.put(serverSession.getSessionId(), serverSession);
        fakeUserSessionIdMap.put(serverSession.getSessionId(), serverSession);
    }


    public void removeSession(ServerSession serverSession) {
        if (normalUserChannels != null) {
            normalUserChannels.remove(serverSession.getChannel());
        }
        logger.info("==UserGroup removeSession   ==,sessionId:{}", serverSession.getSessionId());
        allSessionMap.remove(serverSession.getSessionId());
        fakeUserSessionIdMap.remove(serverSession.getSessionId());
    }
}
